//
//  MANoteWorkDetailViewController.m
//  meiang_edu
//
//  Created by 栋 on 2018/12/31.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//


#import "MANoteWorkDetailViewController.h"

#import "MANoteReplyCell.h"
#import "MAAlertView.h"
#import "MARightTipView.h"
#import "CollectionHShowView.h"
#import "MANoteImageModel.h"
#import "MACompleteStatusModel.h"
#import "MACountContentViewController.h"
@interface MANoteWorkDetailViewController ()

/**
 UIScrollView
 */
@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollView;

/**
 UIScrollView容器
 */
@property (weak, nonatomic) IBOutlet UIView *contentView;

/**
 标题
 */
@property (weak, nonatomic) IBOutlet UILabel *lblTitle;

/**
 发送人
 */
@property (weak, nonatomic) IBOutlet UILabel *lblSender;

/**
 内容
 */
@property (weak, nonatomic) IBOutlet UILabel *lblContent;

/**
 时间
 */
@property (weak, nonatomic) IBOutlet UILabel *lblTime;

/**
 图片容器
 */
@property (weak, nonatomic) IBOutlet UIView *viewImgContent;

/**
 图片展示器,collectionView
 */
@property (weak, nonatomic) CollectionHShowView * viewImageShow;

/**
 图片容器高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutViewImgsHeight;

/**
 图片容器底部约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutViewImgsBottom;

/**
 作业检查标题
 */
@property (weak, nonatomic) IBOutlet UILabel *lblCheckTitle;

/**
 作业检查完成统计
 */
@property (weak, nonatomic) IBOutlet UILabel *lblCheckFinish;

/**
 作业检查未完成统计
 */
@property (weak, nonatomic) IBOutlet UILabel *lblCheckUnFinish;

/**
 作业上传统计
 */
@property (weak, nonatomic) IBOutlet UILabel *lblUploadFinish;

/**
 作业未上传统计
 */
@property (weak, nonatomic) IBOutlet UILabel *lblUploadUnFinish;

/**
 作业检查时间
 */
@property (weak, nonatomic) IBOutlet UILabel *lblCheckTime;

/**
 header数据 详情
 */
@property (nonatomic ,strong) MANoteManageModel * msgDetailmodel;

/**
 上一页传入的数据
 */
@property (nonatomic ,strong) MANoteManageModel * manageModel;

/**
 回复cell 用于计算高度
 */
@property (nonatomic ,strong) MANoteReplyCell * cellCalculate;

@end

@implementation MANoteWorkDetailViewController

#pragma mark - init

+(instancetype)messageDetailViewControllerWith:(MANoteManageModel *)manageModel{
    MANoteWorkDetailViewController * messageVC = [MANoteWorkDetailViewController new];
    messageVC.manageModel = manageModel;
    return messageVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpNav];
    [self setUpImageShowView];
    _mainScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [_mainScrollView.mj_header beginRefreshing];
    [self setHeaderDataWithModel:self.manageModel];
    
}

- (void)setUpNav{
    self.title = [_funcItemModel.function_name stringByReplacingOccurrencesOfString:@"管理" withString:@"详情"];

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(tapRightItem) image:@"reminderbutton_logo" highImage:@"Exclamation point"];
    self.view.backgroundColor = [UIColor whiteColor];
}
//初始化图片容器
- (void)setUpImageShowView{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = [self getImageSize];
    layout.minimumLineSpacing = 4;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    CollectionHShowView * hView = [[CollectionHShowView alloc] initWithNibCell:@"MANoteImageCell" modelName:@"MANoteImageModel" cellSize:[self getImageSize] layout:layout];
    [_viewImgContent addSubview:hView];
    [hView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.right.bottom.mas_equalTo(0);
    }];
    hView.collectionView.scrollEnabled = NO;
    _viewImageShow = hView;
    _viewImageShow.clipsToBounds = YES;
}

- (void)tapRightItem{
    [MARightTipView showWithTips:@"如果您需要删除或停用卡片内容,请长按您所需要操作的卡片"];
}

#pragma mark - 懒加载
- (MANoteReplyCell *)cellCalculate{
    if (!_cellCalculate) {
        _cellCalculate = [[[NSBundle mainBundle] loadNibNamed:@"MANoteReplyCell" owner:nil options:nil] lastObject];
        
    }
    return _cellCalculate;
}

#pragma mark - 网络请求
//header请求
- (void)headerRefresh{
    [self requestData:YES];
}
//footer请求----未使用
- (void)footerRefresh{
    [self requestData:NO];
}
- (void)requestData:(BOOL)new{
    __block NSInteger totoal = 0;
    dispatch_group_t group = dispatch_group_create();
    if (new) {
        totoal ++;
        dispatch_group_enter(group);
        [self requestHeader:^{
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_enter(group);
    [self requestCheckList:new completion:^{
        dispatch_group_leave(group);
    }];
     dispatch_group_enter(group);
    [self requestUploadList:new completion:^{
        dispatch_group_leave(group);
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"dispatch_group_notify");
        if (self.msgDetailmodel) {
            self.contentView.hidden = NO;
        }
        if (new) {
            [self.mainScrollView.mj_header endRefreshing];
        }else{
            [self.mainScrollView.mj_footer endRefreshing];
        }
    });
}
//加载检查数量接口
- (void)requestCheckList:(BOOL)new completion:(void(^)(void))completion{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?type=check",NOTICE_MESSAGE_READ,_manageModel.keyid];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            NSDictionary * value = dataDict[@"value"];
            NSString * unfinished = value[@"unfinished"];

            NSArray * finished = value[@"finished"];
            self.lblCheckFinish.text = [NSString stringWithFormat:@"完成检查:  %@人",finished];
            self.lblCheckUnFinish.text = [NSString stringWithFormat:@"未完成检查:  %@人",unfinished];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
        
    } failure:^(NSError *error) {
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        completion();
    }];
}
//加载上传数量接口
- (void)requestUploadList:(BOOL)new completion:(void(^)(void))completion{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?type=upload",NOTICE_MESSAGE_READ,_manageModel.keyid];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            
            NSDictionary * value = dataDict[@"value"];
            NSString * unfinished = value[@"unfinished"];
            
            NSArray * finished = value[@"finished"];
            self.lblUploadFinish.text = [NSString stringWithFormat:@"完成上传:  %@人",finished];
            self.lblUploadUnFinish.text = [NSString stringWithFormat:@"未完成上传:  %@人",unfinished];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
        
    } failure:^(NSError *error) {
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        completion();
    }];
}
//加载头部基本信息
- (void)requestHeader:(void(^)(void))completion{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?type=作业",MESSAGE_DETAIL,_manageModel.keyid];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dataDict = %@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            self.msgDetailmodel = [MANoteManageModel mj_objectWithKeyValues:dataDict[@"value"]];
            [self setHeaderDataWithModel:self.msgDetailmodel];
            self.lblCheckTitle.text = [NSString stringWithFormat:@"%@统计",self.msgDetailmodel.message_title];
            self.lblCheckTime.text = self.msgDetailmodel.send_time;
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        completion();
    }];
}

#pragma mark - 更新UI
- (void)setHeaderDataWithModel:(MANoteManageModel*)model{
    self.lblTitle.text = model.message_title;
    self.lblSender.text = [NSString stringWithFormat:@"发送人:%@",model.sender_name];
    self.lblContent.text = model.message_content;
    self.lblTime.text = model.send_time;
    NSArray * arrayImgUrl = model.message_image_count.integerValue>0? [model.message_images componentsSeparatedByString:@","]:@[];
    UIImage *placeholderImage = [UIImage imageNamed:@"picture_logo"];
    NSMutableArray * arrayImageModels = [NSMutableArray array];
    for (NSString * url in arrayImgUrl) {
        MANoteImageModel * imgModel = [MANoteImageModel new];
        imgModel.url = url;
        imgModel.placeholderImage = placeholderImage;
        [arrayImageModels addObject:imgModel];
    }
    [_viewImageShow setDataSource:arrayImageModels];

    NSInteger rowCount = arrayImgUrl.count/3;
    if ((arrayImgUrl.count%3) != 0) {
        rowCount += 1;
    }
    
    //图片区域高度
    CGFloat imageContentHeight = [self getImageSize].height * rowCount + (rowCount>0?(4*(rowCount-1)):0);
    self.layoutViewImgsHeight.constant = imageContentHeight;
    if (model.message_image_count.integerValue>0) {
        self.layoutViewImgsBottom.constant = 12;
    }else{
        self.layoutViewImgsBottom.constant = 0;
    }
    [self.view layoutIfNeeded];
}

- (CGSize)getImageSize{
    CGFloat imageWidth = (SCREEN_WIDTH - 4*2-12*2-4*2)/3.0;
    CGFloat imageHeight = imageWidth * (68.0/108);
    return CGSizeMake(imageWidth, imageHeight);
}

#pragma mark - 点击事件
//点击顶部删除
- (IBAction)tapDeleteNoteDetail{
    [MAAlertView showAlertViewWithMessage:@"您确定删除当前消息?" MakeSureBlock:^{
        [MANetwork POSTString:DELETE_MESSAGE bodyString:self.msgDetailmodel.keyid autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
            if (success) {
                [self.navigationController popViewControllerAnimated:YES];
                [MBManager showBriefAlert:@"删除成功"];
            }
        } failure:^(NSError *error) {
            
        }];
    } cancelBlock:^{
        
    }];
}
//点击检查
- (IBAction)tapCheckFinish:(id)sender {
    MACountContentViewController * vc = [MACountContentViewController new];
    vc.model = _msgDetailmodel;
    vc.funcItemModel = self.funcItemModel;
    vc.countType = MACountContentTypeWorkCheck;
    [self.navigationController pushViewController:vc animated:YES];
}

//点击上传
- (IBAction)tapCheckUpload:(id)sender {
    MACountContentViewController * vc = [MACountContentViewController new];
    vc.model = _msgDetailmodel;
    vc.funcItemModel = self.funcItemModel;
    vc.countType = MACountContentTypeWorkUpload;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
